<script>
  import {nextTick, onMounted, onUnmounted, ref, watch, provide} from "vue";
  import {ElMessage} from "element-plus";
  import {useTaskListStore} from "@/pinia/index.js";
  import {useHead} from '@vueuse/head';

  export default {
    setup() {
      // 设置标题、图标、主题颜色
      useHead({
        title: 'WFB·爬塔',
        link: [
          { rel: 'icon', type: 'image/png', href: '/assets/fish/fish1.png' }
        ],
        meta: [
          { name: 'theme-color', content: '#b24646' }
        ]
      })
      const msg = ref(null);
      const chatAndNotificationScrollbarRef = ref(null);
      const harvestNotificationScrollbarRef = ref(null);
      const messageBody = ref({messageType: null, message: {}});
      const chatAndNotificationList = ref([]);
      const harvestNotificationList = ref([]);
      const progressVO = ref({progress: 0});
      const ws = ref(null);
      const playerItemMap = ref(new Map());
      const playerItemList = ref([]);
      const taskList = useTaskListStore();
      const webSocketIsOpen = ref(false);
      const taskType1Grade = ref({});
      const taskType2Grade = ref({});
      const taskType3Grade = ref({});

      const handleEnter = () => {
        sendMsg()
      }

      const initWebsocket = () => {
        let url = "ws://localhost:9001/climbingTowerWebSocket/" + 424907162 + "/" + 1803384152
        ws.value = new WebSocket(url);
        ws.value.onopen = () => {
          console.log("WebSocket is connected")
          webSocketIsOpen.value = true
        }
        ws.value.onmessage = (event) => {
          const messageBody = JSON.parse(event.data)
          console.log(messageBody)
          if (messageBody.messageType === 1 || messageBody.messageType === 2) {
            chatAndNotificationList.value.push(messageBody)
          }
          if (messageBody.messageType === 3) {
            harvestNotificationList.value.push(messageBody)
          }
          if (messageBody.messageType === 4) {
            progressVO.value = messageBody.message
          }
          if (messageBody.messageType === 5) {
            const message = new Map(Object.entries(messageBody.message))
            for (const [key, value] of message.entries()) {
              if (value <= 0) {
                playerItemMap.value.delete(key)
              } else {
                playerItemMap.value.set(key, value)
              }
            }
            playerItemList.value = Array.from(playerItemMap.value.entries()).map(([key, value]) => ({ key, value }))
          }
          if (messageBody.messageType === 6) {
            taskList.cover(messageBody.message)
          }
          if (messageBody.messageType === 7) {
            if (messageBody.message.taskType === 1) {
              taskType1Grade.value = messageBody.message
            }
            if (messageBody.message.taskType === 2) {
              taskType2Grade.value = messageBody.message
            }
            if (messageBody.message.taskType === 3) {
              taskType3Grade.value = messageBody.message
            }
          }
        }
        ws.value.onerror = () => {
          setTimeout(() => {
            if (ws.value.readyState === WebSocket.CLOSED) {
              console.log("WebSocket is error linking again")
              initWebsocket()
            }
          }, 5000)
        }
      }

      onMounted(() => {
        initWebsocket()
      });

      onUnmounted(() => {
        if (ws) {
          console.log("WebSocket is closed")
          ws.value.close()
        }
      });

      watch(chatAndNotificationList, (newList, oldList) => {
        nextTick(() => {
          if (chatAndNotificationScrollbarRef.value) {
            chatAndNotificationScrollbarRef.value.setScrollTop(38 * newList.length)
          }
        })
      }, {deep: true});
      watch(harvestNotificationList, (newList, oldList) => {
        nextTick(() => {
          if (harvestNotificationScrollbarRef.value) {
            harvestNotificationScrollbarRef.value.setScrollTop(38 * newList.length)
          }
        })
      }, {deep: true});
      provide("websocket", ws);

      const sendMsg = () => {
        if (msg.value) {
          messageBody.value.messageType = 4
          messageBody.value.message = msg.value
          ws.value.send(JSON.stringify(messageBody.value))
          msg.value = null
        } else {
          ElMessage({
            showClose: true,
            message: "请输入内容",
            type: "error"
          })
        }
      }

      const stopProgress = () => {
        messageBody.value.messageType = 2
        ws.value.send(JSON.stringify(messageBody.value))
        setTimeout(() => {
          progressVO.value = {progress: 0}
        }, 110)
      }

      return {
        chatAndNotificationList,
        harvestNotificationList,
        msg,
        chatAndNotificationScrollbarRef,
        harvestNotificationScrollbarRef,
        progressVO,
        playerItemList,
        webSocketIsOpen,
        taskType1Grade,
        taskType2Grade,
        taskType3Grade,
        sendMsg,
        handleEnter,
        stopProgress,
      }
    },
  }
</script>

<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right title">
      <el-breadcrumb-item :to="{ path: '/' }" style="font-size:15px;">首页</el-breadcrumb-item>
      <el-breadcrumb-item style="font-size:15px;">爬塔</el-breadcrumb-item>
    </el-breadcrumb>
  </div>
  <el-container style="height: 80vh;">
    <el-aside style="border: 2px rgba(90, 95, 105, 0.9) solid;margin: 5px;border-radius: 25px;">
      <el-menu router class="custom-menu">
        <el-menu-item index="/task/1" class="custom-menu-item">
          <div style="text-align: left;width: 100%;height: 100%">
            <div style="display: flex;justify-content: space-between">
              <span>摸鱼</span>
              <span>{{ taskType1Grade.grade }}</span>
            </div>
            <el-progress style="margin-top: -15px" :percentage="taskType1Grade.currentXpRate" :stroke-width="5" :show-text="false" :duration="10"></el-progress>
          </div>
        </el-menu-item>
        <el-menu-item index="/task/2" class="custom-menu-item">
          <div style="text-align: left;width: 100%;height: 100%">
            <div style="display: flex;justify-content: space-between">
              <span>伐木</span>
              <span>{{ taskType2Grade.grade }}</span>
            </div>
            <el-progress style="margin-top: -15px" :percentage="taskType2Grade.currentXpRate" :stroke-width="5" :show-text="false" :duration="10"></el-progress>
          </div>
        </el-menu-item>
        <el-menu-item index="/task/3" class="custom-menu-item">
          <div style="text-align: left;width: 100%;height: 100%">
            <div style="display: flex;justify-content: space-between">
              <span>烹饪</span>
              <span>{{ taskType3Grade.grade }}</span>
            </div>
            <el-progress style="margin-top: -15px" :percentage="taskType3Grade.currentXpRate" :stroke-width="5" :show-text="false" :duration="10"></el-progress>
          </div>
        </el-menu-item>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header style="border: 2px rgba(90, 95, 105, 0.9) solid;margin: 5px;border-radius: 25px;">
        <div style="text-align: left;margin-top: 2px;">
          {{ progressVO.handlerName == null ? "无任务":progressVO.handlerName }}{{ progressVO.handlerCount == null ? "":"(" + progressVO.handlerCount + ")" }} {{ progressVO.handlerRemainingTime }}
        </div>
        <el-row justify="center" align="middle" :gutter="20">
          <el-col :span="12">
            <el-progress :percentage="progressVO.progress" :stroke-width="25" :text-inside="true" :duration="10" striped></el-progress>
          </el-col>
          <el-col :span="12">
            <el-button bg type="danger" size="small" @click="stopProgress">停止</el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-main style="border: 2px rgba(90, 95, 105, 0.9) solid;margin: 5px;border-radius: 25px;" v-if="webSocketIsOpen">
        <RouterView></RouterView>
      </el-main>
      <el-footer style="border: 2px rgba(90, 95, 105, 0.9) solid; height: 28vh;margin: 5px;border-radius: 25px;">
        <el-row justify="center">
          <el-col :span="12">
            <div style="border: rgba(90, 95, 105, 0.9) 2px solid; width: 99%;height: 200px;margin-top: 5px;">
              <el-scrollbar ref="chatAndNotificationScrollbarRef">
                <div v-for="messageBody in chatAndNotificationList" style="height: 30px;margin: 8px;">
                  <el-tag v-if="messageBody.messageType === 1" type="warning" style="height: 30px;">
                    <div style="margin: 2px;">
                      {{ messageBody.message.time }}
                    </div>
                    <div style="margin: 2px;">
                      {{ messageBody.message.message }}
                    </div>
                  </el-tag>
                  <el-tag v-if="messageBody.messageType === 2" type="info" style="height: 30px;">
                    <div style="margin: 2px;">
                      {{ messageBody.message.userName }} {{ messageBody.message.time }}
                    </div>
                    <div style="margin: 2px;">
                      {{ messageBody.message.message }}
                    </div>
                  </el-tag>
                </div>
              </el-scrollbar>
              <div style="text-align: center;margin-top: 5px;">
                <el-input v-model="msg" style="width: 84%;margin-right: 2px;" @keydown.enter="handleEnter"></el-input>
                <el-button @click="sendMsg">发送</el-button>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div style="border: rgba(90, 95, 105, 0.9) 2px solid; width: 99%;height: 200px;margin-top: 5px;">
              <el-scrollbar ref="harvestNotificationScrollbarRef">
                <div v-for="messageBody in harvestNotificationList" style="height: 30px;margin: 8px;">
                  <el-tag v-if="messageBody.messageType === 3" type="warning" style="height: 30px;">
                    <div style="margin: 2px;">
                      {{ messageBody.message.time }}
                    </div>
                    <div style="margin: 2px;">
                      {{ messageBody.message.message }}
                    </div>
                  </el-tag>
                </div>
              </el-scrollbar>
            </div>
          </el-col>
        </el-row>
      </el-footer>
    </el-container>
    <el-aside style="border: 2px rgba(90, 95, 105, 0.9) solid;margin: 5px;border-radius: 25px;">
      <div v-for="playerItem in playerItemList" :key="playerItem.key" style="margin: 5px;">
        {{ playerItem.key }}*{{ playerItem.value }}
      </div>
    </el-aside>
  </el-container>
</template>

<style scoped>
  .custom-menu {
    background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
    border-radius: 12px;
    padding: 8px 0;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
    border: none;
    height: 100%;
  }
  :deep(.custom-menu-item) {
    color: #000000;
    font-size: 14px;
    font-weight: 500;
    font-family: 'Segoe UI', system-ui;
    margin: 4px 12px;
    border-radius: 8px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }
  :deep(.custom-menu-item:hover) {
    background: linear-gradient(90deg, #fafafa 0%, rgba(10, 30, 54, 0.08) 100%) !important;
    color: #000000 !important;
    transform: translateX(4px);
    box-shadow: 2px 2px 8px rgba(15, 40, 70, 0.08);
  }
  :deep(.custom-menu-item.is-active) {
    background: linear-gradient(90deg, #fafafa 0%, #1680ee 100%) !important;
    color: #000000 !important;
    position: relative;
  }
  :deep(.custom-menu-item.is-active)::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    height: 60%;
    width: 3px;
    background: #000000;
    border-radius: 2px;
  }
</style>